package com.bsoft.gol.editor.service.impl;


import com.bsoft.gol.editor.dao.EditorQuestionnaireTitleDAO;
import com.bsoft.gol.editor.dao.EditorSkipLogicDAO;
import com.bsoft.gol.editor.editor.EditorQuestionnaireTitle;
import com.bsoft.gol.editor.editor.EditorSkipLogic;
import com.bsoft.gol.editor.editor.request.EditorSkipLogicListReq;
import hcn.util.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.bsoft.gol.editor.service.EditorSkipLogicApi;
import com.bsoft.gol.editor.utils.CommonUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;


/**
 * 跳题逻辑表
 */
@Service("editorSkipLogicApi")
@Transactional
public class EditorSkipLogicApiImpl implements EditorSkipLogicApi {
	private static Logger logger = LoggerFactory.getLogger(EditorSkipLogicApiImpl.class);

	@Autowired
	EditorSkipLogicDAO editorSkipLogicDAO;

	@Autowired
	EditorQuestionnaireTitleDAO editorQuestionnaireTitleDAO;

	@Override
	public void addSkipLogic(EditorSkipLogic req) {
		//todo 批量
		editorSkipLogicDAO.save(req);
	}

	/**
	 * 批量保存跳题逻辑
	 *
	 * @param req
	 * @return
	 */
	@Override
	public Map<String, Object> saveBatch(EditorSkipLogic req) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		for (EditorSkipLogicListReq skipLogicListReq : req.getOptions()) {
			EditorSkipLogic editorSkipLogic = new EditorSkipLogic();
			if (CommonUtils.isNull(skipLogicListReq.getOptionId())
					|| CommonUtils.isNull(skipLogicListReq.getTitleAimId())) {
				resMap.put("code", ResultCode.PARAMETERS_EMPTY);
				resMap.put("message", "传入参数不能为空");
				return resMap;
			}
			editorSkipLogic.setSkipId(UUID.randomUUID().toString().replaceAll("-", ""));
			editorSkipLogic.setTitleId(req.getTitleId());
			editorSkipLogic.setOptionId(skipLogicListReq.getOptionId());
			editorSkipLogic.setTitleAimId(skipLogicListReq.getTitleAimId());
			editorSkipLogicDAO.save(editorSkipLogic);
		}

		//将该题目标识为有跳题逻辑
		EditorQuestionnaireTitle editorQuestionnaireTitle = new EditorQuestionnaireTitle();
		editorQuestionnaireTitle.setTitleId(req.getTitleId());
		editorQuestionnaireTitle.setSkipFlag((byte) 1);
		editorQuestionnaireTitleDAO.updateEditorQuestionnaireTitleSkipFlag(req.getTitleId(),(byte) 1);

		resMap.put("code", ResultCode.SUCCESS);
		return resMap;
	}


	@Override
	public void deleteSkipLogic(EditorSkipLogic req) {
		editorSkipLogicDAO.remove(req.getSkipId());
	}

	@Override
	public List<EditorSkipLogic> list(EditorSkipLogic req) {
		return editorSkipLogicDAO.queryEditorSkipLogicListByTitleId(req.getTitleId());
	}
}